#!/usr/bin/env python3
"""
PDF 转 DOCX 转换脚本 (使用 pdf2docx)
先将 PDF 转换为 DOCX，然后由 LibreOffice 将 DOCX 转换为 HTML
"""

import sys
import json
import os
import argparse
from pathlib import Path

try:
    from pdf2docx import Converter
except ImportError:
    print(json.dumps({
        "success": False,
        "error": "pdf2docx library not installed. Please install it with: pip install pdf2docx"
    }))
    sys.exit(1)


def pdf_to_docx(pdf_path: str, output_path: str = None) -> dict:
    """
    使用 pdf2docx 将 PDF 转换为 DOCX
    
    Args:
        pdf_path: PDF 文件路径
        output_path: 可选的输出 DOCX 文件路径，如果不指定则使用默认路径
    
    Returns:
        dict: 包含转换结果的字典
    """
    try:
        if not os.path.exists(pdf_path):
            return {
                "success": False,
                "error": f"PDF file not found: {pdf_path}"
            }
        
        # 如果未指定输出路径，使用默认路径（同目录下，扩展名改为.docx）
        if not output_path:
            output_path = os.path.splitext(pdf_path)[0] + ".docx"
        
        # 确保输出目录存在
        output_dir = os.path.dirname(output_path)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
        
        # 创建转换器并执行转换
        cv = Converter(pdf_path)
        cv.convert(output_path)
        cv.close()
        
        # 检查输出文件是否成功创建
        if not os.path.exists(output_path):
            return {
                "success": False,
                "error": f"Failed to create output file: {output_path}"
            }
        
        file_size = os.path.getsize(output_path)
        
        return {
            "success": True,
            "output_path": output_path,
            "file_size": file_size
        }
    
    except Exception as e:
        return {
            "success": False,
            "error": f"Failed to convert PDF to DOCX: {str(e)}"
        }


def main():
    parser = argparse.ArgumentParser(
        description="Convert PDF to DOCX using pdf2docx"
    )
    parser.add_argument("pdf_path", help="Path to the PDF file to convert")
    parser.add_argument(
        "-o", "--output",
        help="Output DOCX file path (optional)",
        default=None
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output result as JSON"
    )
    
    args = parser.parse_args()
    
    result = pdf_to_docx(args.pdf_path, args.output)
    
    if args.json:
        # 输出 JSON 格式
        print(json.dumps(result, ensure_ascii=False, indent=2))
    else:
        # 输出纯文本格式
        if result["success"]:
            print(f"✓ DOCX file saved to: {result['output_path']}")
            print(f"  File size: {result['file_size']} bytes")
        else:
            print(f"✗ Error: {result['error']}", file=sys.stderr)
            sys.exit(1)


if __name__ == "__main__":
    main()
